package com.rongchuang.autoopendevice.service.impl;

import com.rongchuang.autoopendevice.bean.OrderDetail;
import com.rongchuang.autoopendevice.service.ControlRelayService;
import io.netty.util.internal.StringUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.event.MessageCountAdapter;
import javax.mail.event.MessageCountEvent;

// 处理收到邮件的逻辑
@Component
public class QQMessageProcessing extends MessageCountAdapter {
    @Value("${qiyuanhong.articlenumber}")
    private String articleNumber;
    @Value("${qiyuanhong.subject}")
    private String emailSubject;
    @Value("${email.outbox}")
    private String outbox;
    @Autowired
    ControlRelayService controlRelayService;
    private static final Logger LOGGER = LoggerFactory.getLogger(QQMessageProcessing.class);

    public void messagesAdded(MessageCountEvent ev) {
        Message[] msgs = ev.getMessages();
        LOGGER.info("-------------------接收消息-------------------");
        LOGGER.info("得到 {} 条新消息", msgs.length);
        for (Message msg : msgs) {
            try {
                String subject = msg.getSubject();
                String from = msg.getFrom()[0].toString();
                // 如果不是指定发件箱发过来的消息则退出
                if (!from.contains(outbox)) {
                    return;
                }
                LOGGER.info("Subject: {}", subject);
                if (emailSubject.equals(subject)) {
                    // 获取邮件内容
                    Object content = msg.getContent();

                    // 如果邮件内容是复杂类型（如HTML邮件）
                    if (content instanceof Multipart multipart) {
                        // 遍历多部分内容
                        for (int i = 0; i < multipart.getCount(); i++) {
                            BodyPart bodyPart = multipart.getBodyPart(i);
                            // 检查BodyPart的内容类型
                            if (bodyPart.isMimeType("text/html")) {
                                // 如果是HTML内容
                                String htmlContent = (String) bodyPart.getContent();
                                // 进行HTML内容解析或其他操作
                                // 例如，您可以使用HTML解析器来提取HTML标签中的文本内容
//                                System.out.println("----------multipart HTML----------");

                                OrderDetail orderDetail = analysisContent(htmlContent);
                                if (articleNumber.equals(orderDetail.getArticleNumber())) {
                                    if (!StringUtil.isNullOrEmpty(orderDetail.getDeviceId())){
                                        controlRelayService.openPulse(orderDetail.getDeviceId());
                                        // 已读
                                        msg.setFlag(Flags.Flag.SEEN, true);
                                    }else {
                                        LOGGER.info("设备编号不存在");
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    private OrderDetail analysisContent(String text) {
        LOGGER.info("-------------------开始解析内容-------------------");
        OrderDetail orderDetail = new OrderDetail();
        try {
            Document doc = Jsoup.parse(text);

            // 提取设备编号
            Element deviceIdElement = doc.selectFirst("td:containsOwn(设备编号)");
            String deviceId = null;
            if (deviceIdElement != null) {
                deviceId = deviceIdElement.text().split("：")[1];
            }
            LOGGER.info("设备编号：{}", deviceId);
            orderDetail.setDeviceId(deviceId);

            // 提取订单总金额
            Element amountElement = doc.selectFirst("p:contains(订单总金额)");
            String orderAmount = null;
            if (amountElement != null) {
                orderAmount = amountElement.text().split("：")[1];
            }
            LOGGER.info("订单总金额：{}", orderAmount);
            orderDetail.setOrderAmount(orderAmount);
            // 提取商品名
            Elements productNameElements = doc.select("td[class=td-1]");
            String productName = productNameElements.get(1).text();
            LOGGER.info("商品名：{}", productName);
            orderDetail.setProductName(productName);
            // 提取货号
            Elements articleNumberElements = doc.select("td[class=td-4]");
            String articleNumber = articleNumberElements.get(1).text();
            LOGGER.info("货号：{}", articleNumber);
            orderDetail.setArticleNumber(articleNumber);
            LOGGER.info("-------------------解析完毕-------------------");


        } catch (Exception e) {
            LOGGER.error("解析失败", e);
            LOGGER.info("-------------------失败字符串-------------------");
            LOGGER.info(text);
        }
        return orderDetail;
    }
}
